<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User\BecomeDueModel;
use Carbon\Carbon;
use Illuminate\Http\Request;

class BecomeDueController extends Controller
{
    /**
     * 到期提醒列表
     */
    public function list (Request $request)
    {
        $status = $request->get('status'); // 状态筛选：0-已过期 1-正常 2-已停用
        $query  = BecomeDueModel::query()
                                ->where('user_id', $request->user()->id);

        // 状态筛选
        if ($status !== null) {
            $query->where('status', $status);
        }

        // 获取列表，按到期时间排序
        $list = $query->orderBy('end_at', 'asc')->get();

        // 格式化数据
        $formattedList = $list->map(function ($item) {
            return [
                'id'           => $item->id,
                'name'         => $item->name,
                'price'        => $item->price,
                'cycle'        => $item->cycle,
                'cycle_text'   => $item->cycle_text,
                'svg'          => $item->svg,
                'renew'        => $item->renew,
                'renew_text'   => $item->renew_text,
                'start_at'     => $item->start_at,
                'end_at'       => $item->end_at,
                'remind_days'  => $item->remind_days,
                'status'       => $item->status,
                'remark'       => $item->remark,
                'created_at'   => $item->created_at,
                'updated_at'   => $item->updated_at,
                // 计算剩余天数
                'days_left'    => $this->calculateDaysLeft($item->end_at),
                // 是否需要提醒
                'need_remind'  => $this->needRemind($item->end_at, $item->remind_days),
            ];
        });

        // 统计信息
        $statistics = [
            'total'        => $list->count(),
            'normal'       => $list->where('status', 1)->count(),
            'expired'      => $list->where('status', 0)->count(),
            'need_remind'  => $list->filter(function ($item) {
                return $this->needRemind($item->end_at, $item->remind_days);
            })->count(),
            'total_price'  => number_format($list->sum('price') / 100, 2, '.', ''),
        ];

        return $this->success([
            'list'       => $formattedList->toArray(),
            'statistics' => $statistics,
        ]);
    }

    /**
     * 计算剩余天数
     */
    private function calculateDaysLeft($endAt)
    {
        $now     = Carbon::now()->timestamp;
        $daysLeft = ceil(($endAt - $now) / 86400);
        return max(0, $daysLeft); // 如果已过期，返回0
    }

    /**
     * 判断是否需要提醒
     */
    private function needRemind($endAt, $remindDays)
    {
        $now       = Carbon::now()->timestamp;
        $remindTime = $endAt - ($remindDays * 86400);
        return $now >= $remindTime && $now < $endAt;
    }
}
